package com.julang.check.api.controller;


import com.julang.check.bean.RepeatWordAnalysis;
import com.julang.check.bean.RequestEntity;
import com.julang.check.annotation.NotNeedToken;
import com.julang.check.api.entity.YyHtmlReport;
import com.julang.check.api.entity.YyReportAnalysis;
import com.julang.check.api.service.impl.YyHtmlReportServiceImpl;
import com.julang.check.api.service.impl.YyReportAnalysisServiceImpl;
import com.julang.check.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.julang.check.bean.ResponseEntity.*;
import com.julang.check.controller.BaseController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static com.julang.check.utils.CommonData.*;

/**
 * <p>
 * yy的检测报告分析相关操作
 * </p>
 *
 * @author 赵自强
 * @since 2019-06-05
 */
@RestController
@Api(tags = "PaperYY检测报告详情分析")
@RequestMapping("/api/yy-report-analysis")
public class YyReportAnalysisController extends BaseController {

	@Autowired
	private YyHtmlReportServiceImpl htmlReportService;
	@Autowired
	private YyReportAnalysisServiceImpl reportAnalysisService;

	@ApiOperation("根据yy报告文件的id来解析重复语句和重复词语")
	@ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
	@RequestMapping(value = "/report_analysis", method = {RequestMethod.GET})
	@ResponseBody
	public Result<YyHtmlReport> getAllHtmlFile(@RequestParam(value = "id", required = true) String id) {
		YyHtmlReport re = htmlReportService.getById(id);
		//如果是已经解析过的文档  直接返回解析结果
		if (re.getFileStatus() == 1) {
			return Result.buildSuccess("", re);
		}
		//获取html解析的结果
		List<YyReportAnalysis> list = reportAnalysisService.executeAnalysisSentence(re.getFileName(), id);
		if (list == null) {
			return Result.buildError(CommonData.FAIL, MessageInfo.HTMLANALYSISERROR, re);
		}
		boolean h = reportAnalysisService.saveBatch(list);
		if (h) {
			//更新报告文件记录为已经解析
			String fileName = SingnalData.filePath + System.currentTimeMillis() + ".record";
			RepeatWordAnalysis data = null;
			try {
				//获取关键词出现的次数等信息
				data = reportAnalysisService.getRepeatWordAnalysisData(list, fileName);
			} catch (IOException e) {
				e.printStackTrace();
				return Result.buildError(CommonData.FAIL, MessageInfo.FILEEXCEPTION, re);
			}
			re.setRepetitionsNumber(data.getWordCount());
			re.setDuplicateWordsTotal(data.getList().size());
			re.setReplaceFilePath(fileName);
			System.out.println("解析完成后的记录: " + re.toString());
			htmlReportService.updateHtmlStatusAfterAnalysis(re);
			return Result.buildSuccess("", re);
		} else {
			return Result.buildError(CommonData.FAIL, MessageInfo.MYSQLERROR, re);
		}
	}

	@ApiOperation("根据报告文件的id查询重复原文和语句")
	@ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
	@RequestMapping(value = "/analysis_data", method = {RequestMethod.GET})
	@ResponseBody
	public Result<List<YyReportAnalysis>> getSentenceAndWords(@RequestParam(value = "id", required = true) String id) {
		List<YyReportAnalysis> list = reportAnalysisService.getAnalysisDataByReportId(id);
		return Result.buildSuccess(MessageInfo.SUCCESSINFO, list);
	}

	@ApiOperation("获取关键词设置等相关信息")
	@ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
	@RequestMapping(value = "/analysis_word", method = {RequestMethod.GET})
	@ResponseBody
	public Result<RepeatWordAnalysis> getWordAnalysis(@RequestParam(value = "id", required = true) String id) {
		RepeatWordAnalysis data = null;
		YyHtmlReport report = htmlReportService.getById(id);
		if (report.getFileStatus() == 0) {
			return Result.buildError(CommonData.FAIL, MessageInfo.FILENOTANALYSIS, null);
		}
		try {
			data = RepeatWordAnalysis.parserFromFile(report.getReplaceFilePath());
		} catch (IOException e) {
			e.printStackTrace();
			return Result.buildError(CommonData.FAIL, MessageInfo.FILEEXCEPTION, null);
		}
		return Result.buildSuccess(MessageInfo.SUCCESSINFO, data);
	}

	@ApiOperation("设置关键词的替换词语")
	@ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
	@RequestMapping(value = "/replace_word", method = {RequestMethod.POST})
	@ResponseBody
	public Result<RepeatWordAnalysis> setReplaceWord(@RequestBody RequestEntity.ReplaceWordRequest replaceWord) {
		RepeatWordAnalysis data = null;
		YyHtmlReport report = htmlReportService.getById(replaceWord.getId());
		if (report == null) {
			return Result.buildError(CommonData.FAIL, MessageInfo.HTMLREPORTRECORDNOEXIST, null);
		}
		try {
			String replaceFilePath = report.getReplaceFilePath();
			data = RepeatWordAnalysis.parserFromFile(replaceFilePath);
			boolean v = data.addReplaceWord(replaceWord.getOriginWord(), replaceWord.getReplaceWord());
			if (!v) {
				return Result.buildError(CommonData.FAIL, MessageInfo.REPEATWORDNOTEXIST, data);
			}
			data.saveToFile(replaceFilePath);
		} catch (IOException e) {
			e.printStackTrace();
			return Result.buildError(CommonData.FAIL, MessageInfo.FILEEXCEPTION, null);
		}
		return Result.buildSuccess(MessageInfo.SUCCESSINFO, data);
	}

	@ApiOperation("替换关键词词语 返回重复语句的替换结果")
	@ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
	@RequestMapping(value = "/html_replace", method = {RequestMethod.GET})
	@ResponseBody
	public Result<List<WordReplaceResult>> replaceHtml(@RequestParam(value = "id", required = true) String id) {
		YyHtmlReport report = htmlReportService.getById(id);
		RepeatWordAnalysis data = null;
		try {
			data = RepeatWordAnalysis.parserFromFile(report.getReplaceFilePath());
		} catch (IOException e) {
			e.printStackTrace();
			return Result.buildError(CommonData.FAIL, MessageInfo.FILEEXCEPTION, null);
		}
		List<WordReplaceResult> resultList = reportAnalysisService.getReplaceResult(id, data);
		return Result.buildSuccess(MessageInfo.SUCCESSINFO, resultList);
	}


	@ApiOperation("替换关键词词语 替换后的word文件")
	@ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
	@RequestMapping(value = "/word", method = {RequestMethod.GET})
	@ResponseBody
	@NotNeedToken
	public void replaceWord(@RequestParam(value = "id", required = true) String id, HttpServletResponse response) {
		YyHtmlReport report = htmlReportService.getById(id);
		String wordPath = report.getDocPath();
		String replaceFilePath = report.getReplaceFilePath();
		if (wordPath == null || replaceFilePath == null) {
			return;
		}
		String writePath = System.currentTimeMillis() + ".docx";
		File file = new File(SingnalData.filePath + writePath);
		try {
			file.createNewFile();
			//获取重复词语信息
			RepeatWordAnalysis data = RepeatWordAnalysis.parserFromFile(replaceFilePath);
			//生成替换文档
			XWPFDocument document = WordReplaceUtil.generateWord(data.getList(), wordPath);
			document.write(new FileOutputStream(new File(SingnalData.filePath + writePath)));
			System.out.println("生成文件的地址: " + SingnalData.filePath + writePath);
			//将文件返回客户端
			FileInputStream fileInputStream = new FileInputStream(file);
			OutputStream outputStream = response.getOutputStream();
			response.setContentType("application/x-download");
			response.addHeader("Content-Disposition", "attachment;filename=" + writePath);
			IOUtils.copy(fileInputStream, outputStream);
			outputStream.flush();
			fileInputStream.close();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@ApiOperation("根据id获取重复句")
	@ApiImplicitParam(name = "Authorization", value = "jwt token", required = true, paramType = "header")
	@RequestMapping(value = "/sentences", method = {RequestMethod.POST})
	@ResponseBody
	public Result<Collection<YyReportAnalysis>> methodGetOriginSentence(@RequestBody RequestEntity.RepeatSentenceRequest r) {
		String sentenceIds = r.getSentence();
		if (StringUtils.isBlank(sentenceIds)) {
			return Result.buildError(CommonData.FAIL, MessageInfo.BLANKPOSTPARAM, null);
		}
		String[] ids = sentenceIds.split(DOUSPLITE);
		List<String> list = Arrays.asList(ids);
		Collection<YyReportAnalysis> resultList = reportAnalysisService.listByIds(list);
		return Result.buildSuccess(MessageInfo.SUCCESSINFO, resultList);
	}
}
